package com.jule.robot.service.thread;

import com.jule.core.jedis.JedisPoolWrap;
import com.jule.core.jedis.StoredObjManager;
import com.jule.db.entities.RoomConfigModel;
import com.jule.db.proxy.EntityProxy;
import com.jule.robot.Robot;
import com.jule.robot.config.Config;
import com.jule.robot.service.holder.*;
import com.jule.robot.util.RandomTools;
import com.jule.robot.util.RunTime;
import com.jule.robot.valve.gate.RobotConfigHandler;
import com.jule.robot.valve.gate.RobotThreadPoolManager;
import com.jule.teenpatti.base.enums.RedisConst;
import com.jule.teenpatti.base.model.RoomTableRelationModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 检查房间是否需要加入机器人
 */
public class CheckTableIsNeedRobot implements Runnable {
    private final static Logger logger = LoggerFactory.getLogger(CheckTableIsNeedRobot.class);
    private int gameId;

    public CheckTableIsNeedRobot(int gameId){
        this.gameId = gameId;
    }

    public void run() {
        try {
            RunTime rumTime = new RunTime("CheckTableIsNeedRobot");
            for (RoomConfigModel roomConfigModel : RoomConfigHolder.getInstance().getAllRoomConfig()) {
                String roomId = roomConfigModel.getRoomId();
                String key4RoomTableRelation = new StringBuilder().append(RedisConst.TABLE_INSTANCE.getProfix()).append(gameId).append(roomId).toString();
                Map<String, String> tableMap = JedisPoolWrap.getInstance().hGetAll(key4RoomTableRelation);
                for (String key : tableMap.keySet()) {
                    RoomTableRelationModel model = StoredObjManager.getStoredObjInMap(RoomTableRelationModel.class, key4RoomTableRelation, key);
                    if (null != model) {
                        String tableId = model.getTableId();

                        String key4tableSeat = new StringBuilder().append(RedisConst.TABLE_SEAT.getProfix()).append(gameId).append(roomId).append(tableId).toString();
                        Map<String, String> seatMap = JedisPoolWrap.getInstance().hGetAll(key4tableSeat);

                        if(logger.isInfoEnabled()){
                            if(seatMap.size() > 0 && seatMap.size() <= 2) {
                                boolean isHaveRealUser = false;
                                for(String userId : seatMap.values()){
                                    if (!RobotUserHolder.getRobotMap().containsKey(userId)) {
                                        isHaveRealUser = true; //桌子上有真人玩家
                                        break;
                                    }
                                }
                                logger.info("发现有人的桌子，key4tableSeat->{}, seatMapSize->{}, isHaveRealUser->{}", key4tableSeat, seatMap.size(), isHaveRealUser);
                            }
                        }

                        if(null != seatMap && seatMap.size() >= 1 && seatMap.size() <= 2){
                            //开一个新线程执行单桌的补位检查，用以保证现在所处的大循环能够快速结束，以免造成每2秒执行一次的大循环发生并发堆积的情况
                            RobotThreadPoolManager.getInstance().addTask(new CheckSingleTableIsNeedRobot(gameId, roomId, tableId, roomConfigModel.getAnte()));
                        }
                    }
                }
            }
            //logger.debug("totalOnLinePlayer = " + totalOnLinePlayer);
            rumTime.getSecsBuyAlreadyRun(1);
        } catch (Exception ex) {
            logger.error("CheckTableIsNeedRobot ERROR, msg = " + ex.getMessage(), ex);
        }
        finally {
//            logger.warn("CheckTableIsNeedRobot Success. gameId->{}", gameId);
        }
    }

    //region 注释并迁移走的joinRobot方法。
    /*
     * 注释by gx 20181001，该方法转移到 RobotClietnHoler 类中。
     */
//    private void joinRobot(int gameId, String roomId, String tableId) throws InterruptedException {
//        String userId = RobotUserHolder.getUser("入桌陪打,gameId="+gameId+",roomId="+roomId+",tableId="+tableId);
//
////        long minBuyIn = RobotConfigHandler.getRobotCommonConfig().getBuyinMin();
////        long maxBuyIn = RobotConfigHandler.getRobotCommonConfig().getBuyinMax();
////        long buyInScoreRate = getRandomNum((int)(maxBuyIn - minBuyIn)) + minBuyIn;
//        RoomConfigModel roomConfig = RoomConfigHolder.getInstance().getRoomConfig(roomId);
//        long minScore4JoinTable = roomConfig.getMinScore4JoinTable();
//        long ante = roomConfig.getAnte();
//        double randomDouble = RandomTools.getRandomDouble(0.39);
//        double buyInScore = (ante * 10 * 20) * (RandomTools.getRandomDouble(2.60) + 0.79);
//
//        //获得买入货币
//        com.jule.db.entities.User user = EntityProxy.OBJ.get(userId, com.jule.db.entities.User.class);
//        if(null != user){
//            boolean isSuccAddMoney = RobotMoneyPoolHolder.robotBuyinFromPool(gameId+"", userId, user, buyInScore);
//
//            logger.info("Need Join Robot, userId = " + userId + ", roomId = " + roomId + ", tableId = " + tableId+", buyInScore = "+ buyInScore
//                    +", MinScore4JoinTable->"+minScore4JoinTable+". randomDouble->"+randomDouble+", isSuccSetMoney->"+isSuccAddMoney);
//
//            //给机器人账号增加所需代入的货币
//            if(isSuccAddMoney){
//                new Robot(gameId, userId, roomId, tableId);
//            }else{
//                RobotUserHolder.addUser(userId);
//                logger.error("补位机器人失败，因：获取货币失败。userId->{}", userId);
//            }
//        }else{
//            logger.error("补位机器人失败，因：在DB中找不到机器人账号。userId->{}", userId);
//        }
//    }
    //endregion

    /**
     * 判断桌内有没有机器人
     */
    private int getRobotNum(Map<String, String> seatMap) {
        int robotNum = 0;
        Iterator<Map.Entry<String, String>> iter = seatMap.entrySet().iterator();
        while (iter.hasNext()) {
            String userId = iter.next().getValue();
            if (RobotUserHolder.getRobotMap().containsKey(userId)) {
                robotNum++;
            }
        }
        return robotNum;
    }

    public long getRandomNum(int maxNum){
        Random random = new Random(System.currentTimeMillis()+System.nanoTime());
        return random.nextInt(maxNum)+1;
    }
}
